package com.xinke.juc.case04;

import com.xinke.juc.util.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author：xinke
 * @Date：2025/10/5
 * @Desc: 公平锁
 */
@Slf4j
public class ReentrantLock06 {
    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock(true);
        lock.lock();
        for (int i = 0; i < 500; i++) {
            new Thread(() -> {
                lock.lock();
                try {
                    log.info(Thread.currentThread().getName() + " running...");
                } finally {
                    lock.unlock();
                }
            }, "t" + i).start();
        }
        // 1s 之后去争抢锁
        Sleeper.sleep(1);
        new Thread(() -> {
            log.info(Thread.currentThread().getName() + " start...");
            lock.lock();
            try {
                log.info(Thread.currentThread().getName() + " running...");
            } finally {
                lock.unlock();
            }

        }, "强行插入").start();
        lock.unlock();
    }

}
